package hunan.qianyuan.codefatherback.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import hunan.qianyuan.codefatherback.annotation.AuthCheck;
import hunan.qianyuan.codefatherback.common.BaseResponse;
import hunan.qianyuan.codefatherback.common.DeleteRequest;
import hunan.qianyuan.codefatherback.common.ResultUtils;
import hunan.qianyuan.codefatherback.config.CosClientConfig;
import hunan.qianyuan.codefatherback.constant.UserConstant;
import hunan.qianyuan.codefatherback.exception.BusinessException;
import hunan.qianyuan.codefatherback.exception.ErrorCode;
import hunan.qianyuan.codefatherback.exception.ThrowUtils;
import hunan.qianyuan.codefatherback.manager.CosManager;
import hunan.qianyuan.codefatherback.model.dto.user.*;
import hunan.qianyuan.codefatherback.model.vo.LoginUserVO;
import hunan.qianyuan.codefatherback.model.vo.UserInfoVO;
import hunan.qianyuan.codefatherback.model.vo.UserVO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import hunan.qianyuan.codefatherback.model.entity.User;
import hunan.qianyuan.codefatherback.service.UserService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
/**
 * 用户 控制层。
 *
 * @author qianyaun
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CosManager cosManager;
    @Autowired
    private CosClientConfig cosClientConfig;

    @PostMapping("/register")
    public BaseResponse<Long> register(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        long userId = userService.userRegister(userAccount, userPassword, checkPassword);
        ThrowUtils.throwIf(userId < 0, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(userId);
    }
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 创建用户
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(userAddRequest, user);
        // 默认密码 123456
        final String DEFAULT_PASSWORD = "123456";
        String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（仅管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtil.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户封装列表（仅管理员）
     *
     * @param userQueryRequest 查询请求参数
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long pageNum = userQueryRequest.getPageNum();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(Page.of(pageNum, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        // 数据脱敏
        Page<UserVO> userVOPage = new Page<>(pageNum, pageSize, userPage.getTotalRow());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

    /**
     * 获取用户信息(用户个人中心)
     */
    @GetMapping("/get/userInfo")
    public BaseResponse<UserInfoVO> getUserInfoVO(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtil.copyProperties(loginUser, userInfoVO);
        return ResultUtils.success(userInfoVO);
    }

    /**
     * 更新用户信息(用户个人中心)
     */

    @PostMapping("/updateUserInfo")
    public BaseResponse<Boolean> updateUserInfo(@RequestBody UserInfoUpdateRequestDTO userInfoUpdateRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        loginUser.setUserAvatar(userInfoUpdateRequest.getUserAvatar());
        loginUser.setUserName(userInfoUpdateRequest.getUserName());
        loginUser.setUserProfile(userInfoUpdateRequest.getUserProfile());
        boolean result = userService.saveOrUpdate(loginUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 获取所有用户信息
     *
     * @return List<UserVO>
     */
    @GetMapping("/getAllUserVOInfo")
    public BaseResponse<List<UserVO>> getAllUserVOInfo() {
        List<User> userList = userService.list();
        List<UserVO> userVOList = userService.getUserVOList(userList);
        return ResultUtils.success(userVOList);
    }

    /**
     * 用户上传头像接口
     *
     * @param multipartFile 文件
     * @param request       请求
     * @return 头像地址
     */
    @PostMapping("/upload/userAvatar")
    public BaseResponse<String> UploadUserAvatar(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        String fileName = multipartFile.getOriginalFilename();
        String uuid = RandomUtil.randomString(16);
        User loginUser = userService.getLoginUser(request);

        // 获取旧头像路径
        String oldAvatarUrl = loginUser.getUserAvatar();
        if (StrUtil.isNotEmpty(oldAvatarUrl)) {
            String replace = oldAvatarUrl.replace(cosClientConfig.getHost(), "");
            cosManager.deleteObject(replace);
        }

        fileName = String.format("%s.%s",
                uuid, (StrUtil.isEmpty(FileUtil.getSuffix(fileName)) ? "webp" : FileUtil.getSuffix(fileName)));
        String filePath = String.format("/userAvatar/%s/%s", loginUser.getId(), fileName);
        File file = null;
        try {
            file = File.createTempFile(fileName, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filePath, file);
            return ResultUtils.success(cosClientConfig.getHost() + "/" + filePath);
        } catch (Exception e) {
            log.error("file upload error , file path = {}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, file path = {}", filePath);
                }
            }
        }
    }

}
